package com.yl.nettylearning.netty.day09;

import com.yl.nettylearning.netty.day08.StudentPOJO;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;

/**
 * @author yangl
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        int random = new Random().nextInt(3);
        StudentInfo.MyMessage studentInfo = null;
        if(0 == random){
            studentInfo = StudentInfo.MyMessage.newBuilder().setDataType(StudentInfo.MyMessage.DataType.StudentType)
                    .setStudent(StudentInfo.Student.newBuilder().setId(1).setName("张三").build()).build();
        } else {
            studentInfo = StudentInfo.MyMessage.newBuilder().setDataType(StudentInfo.MyMessage.DataType.WorkerType)
                    .setWorker(StudentInfo.Worker.newBuilder().setId(1).setName("李四").setAge(55).build()).build();
        }
        ctx.channel().writeAndFlush(studentInfo);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf)msg;
        System.out.println("服务器回复的消息：" + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器的地址：" + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
